'use client'

import React, { useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { useSession } from 'next-auth/react'
import Link from 'next/link'
import Button from '@/components/ui/Button'
import { toast } from 'react-hot-toast'
import { ArrowLeftIcon } from '@heroicons/react/24/outline'

interface ChoiceOption {
  id: string;
  text: string;
}

interface MultipleChoiceContent {
  question?: string;
  options?: ChoiceOption[];
  correctAnswerId?: string | null;
  points?: number;
  answerExplanation?: string;
  explanationVisibleToStudent?: boolean;
}

interface FillInBlankContent {
  question?: string;
  standardAnswers?: string[];
  matchCase?: boolean;
  points?: number;
  answerExplanation?: string;
  explanationVisibleToStudent?: boolean;
}

interface GeneralStageContent {
  points?: number;
  answerExplanation?: string;
  explanationVisibleToStudent?: boolean;
}

interface Stage {
  id: string;
  title: string;
  description: string | null;
  type: string;
  order: number;
  content: MultipleChoiceContent | FillInBlankContent | GeneralStageContent | string | any;
}

interface StageSubmissionData {
  id: string;
  stageId: string;
  answer: any;
  score: number | null;
  feedback: string | null;
  submittedAt: string | null;
  stage: Stage;
}

interface SubmissionDetail {
  id: string;
  status: string;
  score: number | null;
  submittedAt: string | null;
  user: {
    id: string;
    name: string | null;
    email: string;
  };
  experiment: {
    id: string;
    title: string;
  };
  stageSubmissions: StageSubmissionData[];
}

export default function SubmissionDetailPage() {
  const params = useParams();
  const router = useRouter();
  const { data: session, status: sessionStatus } = useSession();

  const experimentId = params.id as string;
  const submissionId = params.submissionId as string;

  const [submissionDetail, setSubmissionDetail] = useState<SubmissionDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isUpdating, setIsUpdating] = useState(false);

  useEffect(() => {
    if (sessionStatus === 'loading') return;
    if (sessionStatus === 'unauthenticated') {
      router.replace('/login');
      return;
    }
    // 只有教师和管理员可以查看
    if (session?.user?.role !== 'TEACHER' && session?.user?.role !== 'ADMIN') {
      toast.error('您没有权限查看此页面。');
      router.replace(`/experiments/${experimentId}`);
      return;
    }

    if (experimentId && submissionId) {
      const fetchSubmissionDetail = async () => {
        setLoading(true);
        setError(null);
        try {
          const response = await fetch(`/api/experiments/${experimentId}/submissions/${submissionId}`);
          if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            throw new Error(errorData.message || `获取提交详情失败 (${response.status})`);
          }
          const data = await response.json();
          setSubmissionDetail(data.submission);
        } catch (err: any) {
          console.error('获取提交详情错误:', err);
          setError(err.message);
          toast.error(err.message || '获取提交详情失败');
        }
        setLoading(false);
      };
      fetchSubmissionDetail();
    }
  }, [experimentId, submissionId, sessionStatus, session, router]);

  const handleScoreChange = async (stageSubmissionId: string, newScore: string | number) => {
    const scoreValue = newScore === '' ? null : parseFloat(newScore as string);
    if (submissionDetail) {
        setSubmissionDetail(prev => {
            if (!prev) return null;
            return {
                ...prev,
                stageSubmissions: prev.stageSubmissions.map(ss => 
                    ss.id === stageSubmissionId ? { ...ss, score: scoreValue } : ss
                )
            };
        });
    }
  };

  const handleFeedbackChange = (stageSubmissionId: string, newFeedback: string) => {
    if (submissionDetail) {
        setSubmissionDetail(prev => {
            if (!prev) return null;
            return {
                ...prev,
                stageSubmissions: prev.stageSubmissions.map(ss => 
                    ss.id === stageSubmissionId ? { ...ss, feedback: newFeedback } : ss
                )
            };
        });
    }
  };

  const handleSubmitGrading = async () => {
    if (!submissionDetail) return;
    setIsUpdating(true);
    toast.loading('正在保存评分...', { id: 'grading' });

    const gradingData = submissionDetail.stageSubmissions.map(ss => ({
        stageSubmissionId: ss.id,
        score: ss.score,
        feedback: ss.feedback,
    }));

    try {
      const response = await fetch(`/api/experiments/${experimentId}/submissions/${submissionId}/grade` , {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ grades: gradingData }),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || '保存评分失败');
      }
      const updatedSubmission = await response.json();
      setSubmissionDetail(updatedSubmission.submission); // 更新总分和状态
      toast.success('评分已保存', { id: 'grading' });
    } catch (err: any) {
      console.error('保存评分错误:', err);
      toast.error(err.message || '保存评分失败', { id: 'grading' });
    }
    setIsUpdating(false);
  };

  const renderStageAnswer = (stageSubmission: StageSubmissionData) => {
    const { stage, answer: rawAnswer } = stageSubmission;
    let studentAnswerParsed: any = {};
    
    if (typeof rawAnswer === 'string' && rawAnswer.trim() !== '') {
        try {
            studentAnswerParsed = JSON.parse(rawAnswer);
        } catch (e) {
            console.error("[SubmissionDetail] Failed to parse student answer JSON:", rawAnswer, e);
            // If parsing fails, and it's a FILE_UPLOAD, maybe the rawAnswer itself is a URL string
            if (stage.type === 'FILE_UPLOAD' && typeof rawAnswer === 'string' && rawAnswer.startsWith('http')) {
                studentAnswerParsed = rawAnswer; // Treat as direct URL
            } else {
                studentAnswerParsed = { error: "Failed to parse student answer", rawContent: rawAnswer };
            }
        }
    } else if (rawAnswer) { // If rawAnswer is not a string but exists (e.g. already an object from somewhere)
        studentAnswerParsed = rawAnswer;
    }

    let stageContentParsed: any = {};
    if (stage.content && typeof stage.content === 'string' && stage.content.trim() !== '') {
        try { stageContentParsed = JSON.parse(stage.content); } catch (e) { stageContentParsed = {}; }
    } else if (stage.content) {
        stageContentParsed = stage.content;
    }

    switch (stage.type) {
      case 'MULTIPLE_CHOICE':
        const mcContent = stageContentParsed as MultipleChoiceContent;
        const studentSelectedOptionId = studentAnswerParsed?.selectedOption;
        
        if (mcContent && mcContent.options && Array.isArray(mcContent.options)) {
          return (
            <div className="space-y-2 mt-2">
              {mcContent.question && <p className="text-sm font-medium text-gray-700 mb-1">题目: {mcContent.question}</p>}
              <ul className="space-y-1">
                {mcContent.options.map(option => {
                  const isSelectedByStudent = option.id === studentSelectedOptionId;
                  const isCorrectAnswer = option.id === mcContent.correctAnswerId;
                  let itemClass = "text-sm p-2 rounded-md flex justify-between items-center border";
                  let correctnessIndicator = "";
                  if (isSelectedByStudent && isCorrectAnswer) {
                    itemClass += " bg-green-50 border-green-300 text-green-700";
                    correctnessIndicator = "(学生选择 - 正确)";
                  } else if (isSelectedByStudent && !isCorrectAnswer) {
                    itemClass += " bg-red-50 border-red-300 text-red-700";
                    correctnessIndicator = "(学生选择 - 错误)";
                  } else if (isCorrectAnswer) {
                    itemClass += " bg-blue-50 border-blue-300 text-blue-700";
                    correctnessIndicator = "(正确答案)";
                  } else {
                    itemClass += " bg-gray-50 border-gray-200 text-gray-800";
                  }
                  return (
                    <li key={option.id} className={itemClass}>
                      <span>{option.text}</span>
                      {correctnessIndicator && <span className="text-xs ml-2">{correctnessIndicator}</span>}
                    </li>
                  );
                })}
                </ul>
              {!studentSelectedOptionId && <p className="text-xs text-gray-500 italic mt-1">学生未选择任何选项。</p>}
            </div>
          );
        }
        return <pre className="bg-gray-50 p-3 rounded-md text-sm text-gray-800 whitespace-pre-wrap break-all">{JSON.stringify(studentAnswerParsed, null, 2) || '答案格式错误或未作答'}</pre>;

      case 'TEXT_INPUT':
      case 'FILL_IN_BLANK':
        const studentText = studentAnswerParsed?.textInput || (typeof studentAnswerParsed === 'string' ? studentAnswerParsed : '');
        return <p className="text-sm text-gray-800 bg-gray-50 p-3 rounded-md whitespace-pre-wrap break-words">{studentText || '未填写'}</p>;

      case 'FILE_UPLOAD':
        const fileUrl = studentAnswerParsed?.fileUrl || (typeof studentAnswerParsed === 'string' && studentAnswerParsed.startsWith('http') ? studentAnswerParsed : null);
        const fileName = studentAnswerParsed?.fileName || (fileUrl ? fileUrl.substring(fileUrl.lastIndexOf('/') + 1) : '查看文件');
        if (fileUrl) {
          return (
            <a href={fileUrl} target="_blank" rel="noopener noreferrer" className="text-primary-600 hover:underline">
              {fileName}
            </a>
          );
        } 
        // If studentAnswerParsed.rawContent contains the JSON string that failed to parse initially
        if(studentAnswerParsed?.rawContent) {
            return <p className="text-sm text-gray-600">学生提交: {studentAnswerParsed.rawContent} (无法识别为有效文件链接)</p>;
        }
        return <p className="text-sm text-gray-500 italic">未上传文件或文件链接无效</p>;

      case 'CODE':
         if (studentAnswerParsed && typeof studentAnswerParsed.code !== 'undefined') {
          return <pre className="bg-gray-900 text-white p-3 rounded-md text-sm whitespace-pre-wrap break-all">{studentAnswerParsed.code || '// 未提交代码'}</pre>;
        }
        return <pre className="bg-gray-50 p-3 rounded-md text-sm text-gray-800 whitespace-pre-wrap break-all">{JSON.stringify(studentAnswerParsed, null, 2) || '答案格式错误或未作答'}</pre>;

      default:
        if (studentAnswerParsed?.rawContent) {
            return <pre className="bg-gray-50 p-3 rounded-md text-sm text-red-600 whitespace-pre-wrap break-all">无法解析学生答案: {studentAnswerParsed.rawContent}</pre>;
        } 
        return <pre className="bg-gray-50 p-3 rounded-md text-sm text-gray-800 whitespace-pre-wrap break-all">{rawAnswer || '未作答'}</pre>;
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-primary-600"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center text-red-600">
        <p className="text-xl mb-4">错误: {error}</p>
        <Link href={`/experiments/${experimentId}?tab=students`}>
          <Button variant="outline">返回学生列表</Button>
        </Link>
      </div>
    );
  }

  if (!submissionDetail) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center">
        <p className="text-xl text-gray-700 mb-4">未找到提交记录。</p>
        <Link href={`/experiments/${experimentId}?tab=students`}>
          <Button variant="outline">返回学生列表</Button>
        </Link>
      </div>
    );
  }
  
  const overallScore = submissionDetail.stageSubmissions.reduce((acc, ss) => acc + (ss.score || 0), 0);

  return (
    <div className="max-w-4xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
      <div className="mb-6">
        <Link 
          href={`/experiments/${experimentId}?tab=students`}
          className="inline-flex items-center text-sm text-primary-600 hover:text-primary-800 mb-4"
        >
          <ArrowLeftIcon className="h-4 w-4 mr-1" />
          返回学生列表
        </Link>
        <h1 className="text-3xl font-bold text-gray-900">批改实验提交</h1>
      </div>

      <div className="bg-white shadow overflow-hidden sm:rounded-lg mb-6">
        <div className="px-4 py-5 sm:px-6">
          <div className="flex flex-wrap justify-between items-center">
            <div>
                <h2 className="text-xl font-semibold text-gray-800">{submissionDetail.experiment.title}</h2>
                <p className="text-sm text-gray-600 mt-1">
                    学生: {submissionDetail.user?.name || submissionDetail.user?.email} ({submissionDetail.user?.email})
                </p>
            </div>
            <div className="text-right mt-2 sm:mt-0">
                <p className="text-sm text-gray-600">
                    提交状态: <span className={`font-medium ${submissionDetail.status === 'GRADED' ? 'text-green-600' : 'text-yellow-600'}`}>{submissionDetail.status}</span>
                </p>
                <p className="text-sm text-gray-600">
                    提交时间: {submissionDetail.submittedAt ? new Date(submissionDetail.submittedAt).toLocaleString() : '未完成'}
                </p>
                <p className="text-lg font-semibold text-gray-800 mt-1">
                    总分: {submissionDetail.score ?? overallScore} / {submissionDetail.stageSubmissions.length > 0 ? submissionDetail.stageSubmissions.reduce((acc, s) => acc + (s.stage.content?.maxScore || 10), 0) : 0}
                </p>
            </div>
          </div>
        </div>
      </div>

      <div className="space-y-6">
        {submissionDetail.stageSubmissions.sort((a,b) => a.stage.order - b.stage.order).map((ss, index) => (
          <div key={ss.id} className="bg-white shadow sm:rounded-lg overflow-hidden">
            <div className="px-4 py-5 sm:p-6">
              <h3 className="text-lg font-medium leading-6 text-gray-900">
                阶段 {index + 1}: {ss.stage.title}
              </h3>
              <p className="mt-1 text-sm text-gray-500">{ss.stage.description}</p>
              
              <div className="mt-4 border-t border-gray-200 pt-4">
                <h4 className="text-md font-medium text-gray-700 mb-2">学生答案:</h4>
                {renderStageAnswer(ss)}
              </div>

              <div className="mt-4">
                <label htmlFor={`score-${ss.id}`} className="block text-sm font-medium text-gray-700">
                  得分 (满分: {ss.stage.content?.maxScore || 10})
                </label>
                <input 
                  type="number"
                  id={`score-${ss.id}`}
                  name={`score-${ss.id}`}
                  value={ss.score === null ? '' : ss.score}
                  onChange={(e) => handleScoreChange(ss.id, e.target.value)}
                  className="mt-1 block w-full sm:w-1/2 md:w-1/3 rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                  min="0"
                  max={ss.stage.content?.maxScore || 10}
                  step="0.1"
                />
              </div>

              <div className="mt-4">
                <label htmlFor={`feedback-${ss.id}`} className="block text-sm font-medium text-gray-700">
                  评语/反馈
                </label>
                <textarea 
                  id={`feedback-${ss.id}`}
                  name={`feedback-${ss.id}`}
                  rows={3}
                  value={ss.feedback || ''}
                  onChange={(e) => handleFeedbackChange(ss.id, e.target.value)}
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                  placeholder="请输入对该阶段提交的评语"
                />
              </div>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-8 flex justify-end">
        <Button 
          onClick={handleSubmitGrading}
          disabled={isUpdating}
          variant="primary"
        >
          {isUpdating ? '保存中...' : '确认并保存评分'}
        </Button>
      </div>
    </div>
  )
} 